package org.xshop.service.impl;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.springframework.cache.annotation.CacheConfig;
import org.xshop.mapper.TStoreMapper;
import org.xshop.model.TStore;
import org.xshop.service.ITStoreService;

import com.weibo.api.motan.config.springsupport.annotation.MotanService;

import top.ibase4j.core.base.BaseServiceImpl;
import top.ibase4j.core.support.Pagination;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.LocationUtil;

/**
 * <p>
 * 店铺 服务实现类
 * </p>
 *
 * @author ShenHuaJie
 * @since 2018-03-01
 */
@MotanService(interfaceClass = ITStoreService.class)
@CacheConfig(cacheNames = "TStore")
public class StoreService extends BaseServiceImpl<TStore, TStoreMapper> implements ITStoreService {

	@Override
	public Object getAllStore(Map<String, Object> param) {
		int pageNum = param.get("pageNum") == null ? 1 : Integer.parseInt(param.get("pageNum").toString());
		int pageSize = 10;
		param.put("offset", (pageNum - 1) * pageSize);
		param.put("limit", pageSize);
		
		Pagination<TStore> page = super.query(param);
		BigDecimal lon = null;
		BigDecimal lat = null;
		if (lon == null && lat == null && DataUtil.isNotEmpty(param.get("mapLon"))
				&& DataUtil.isNotEmpty(param.get("mapLat"))) {
			lon = new BigDecimal(param.get("mapLon").toString());
			lat = new BigDecimal(param.get("mapLat").toString());
		}
		List<TStore> storeList = page.getRecords();
		if (lon != null && lat != null) {
			for (int i = 0; i < storeList.size(); i++) {
				TStore store = page.getRecords().get(i);
				if (store.getStoreLon() != null && store.getStoreLat() != null) {
					BigDecimal distance = new BigDecimal(
							LocationUtil.getDistance(store.getStoreLon(), store.getStoreLat(), lon, lat));
					store.setDistance(distance.setScale(2, BigDecimal.ROUND_HALF_UP));
				}
			}
			// 距离排序
			Collections.sort(storeList, new Comparator<TStore>() {
				@Override
				public int compare(TStore o1, TStore o2) {
					return o1.getDistance().subtract(o2.getDistance()).intValue();
				}
			});
		}
		return page;
	}

}